# coding=utf-8

from rest_framework.decorators import APIView
from rest_framework.response import Response

from files.response_content import IMAGE_TOO_BIG_TO_UPLOAD, FAILED_TO_GET_FILE, UPLOAD_FAILED, FILE_DOES_NOT_IMAGE
from utils.decorators import need_login
from utils.shortcuts import http_400_response
from .aliyun_oss import AliyunOSS
from .serializers import ImageSer

img_type = ['jpg', 'png', 'bmp', 'jpeg', 'gif']


class UploadImageView(APIView):
    @need_login
    def post(self, request, **kwargs):
        a = AliyunOSS()
        file_content = request.FILES.get("file", None)
        if not file_content:
            return http_400_response(FAILED_TO_GET_FILE)
        file_type = str(file_content.name).split('.', 1)[-1]
        if file_type not in img_type:
            return http_400_response(FILE_DOES_NOT_IMAGE)
        # 如果文件超过5（5242880字节）则返回文件过大
        if len(file_content) >= 5242880:
            return http_400_response(IMAGE_TOO_BIG_TO_UPLOAD)

        file_path = a.upload_pic("images/1/", file_content)

        if file_path:
            ser = ImageSer(data={
                'desc': '',
                'image_size': len(file_content),
                'image': file_path[1:],
                'url': 'http://img.laoyaoguai.com.cn' + file_path,
            })
            if ser.is_valid():
                ser.save()
            else:
                return http_400_response(ser.errors)

            return Response({"image_path": 'http://img.laoyaoguai.com.cn' + file_path})
        else:
            return http_400_response(UPLOAD_FAILED)
